/**
 *上海交大-鹏越惊虹
 */

package org.infosec.lc.exercises.threads;

import java.util.concurrent.TimeUnit;

/**  
 * @Title: Deadlock.java
 * @Package org.infosec.lc.exercises.threads.Deadlock
 * @Description: String对象不能作为synchrozied的锁变量
 * 				两种导致隐性死锁的情况：加锁次序和占有并等待。
 * @author 林超 
 * @date Apr 28, 2013 3:11:57 PM
 * @version V1.0  
 */
public class Deadlock {

	/**
	 * @Title: main
	 * @Description: TODO
	 */
	public static void main(String[] args) {
		final Object resource1 = "resource1";   //String对象不能作为synchrozied的锁变量
		final Object resource2 = "resource2";
		
		Thread t1 = new Thread(new Runnable() {
			
			public void run() {
				synchronized (resource1) {
					System.out.println(Thread.currentThread().getName()+"  A点");
					synchronized (resource2) {
						System.out.println(Thread.currentThread().getName()+"  B点");
						while(true){
							System.out.println(Thread.currentThread().getName()+"  C点");
							try {
								TimeUnit.SECONDS.sleep(1);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						}
					}
				}
			}
		},"thread-1");
		
		Thread t2 = new Thread(new Runnable(){

			public void run() {
				synchronized (resource2) {
					System.out.println(Thread.currentThread().getName()+"  A点");
					synchronized (resource1) {
						System.out.println(Thread.currentThread().getName()+"  B点");
						while(true){
							System.out.println(Thread.currentThread().getName()+"  C点");
							try {
								TimeUnit.SECONDS.sleep(1);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						}
					}
				}
			}},"thread-2");
		
		System.out.println(Thread.currentThread().getName()+"  A点");
		t1.start();
		t2.start();
		System.out.println(Thread.currentThread().getName()+"  B点");
		try {
			TimeUnit.SECONDS.sleep(2);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		System.out.println(t1.getName()+" "+t1.getState());   //BLOCKED
		System.out.println(t2.getName()+" "+t2.getState());
		System.out.println(Thread.currentThread().getName()+"  C点");
	}

}
/**Code End*/